<template>
	<div class="new-medical-record-container">
		<!-- 页面标题 -->
		<div class="page-header">
			<h1>新建医疗档案</h1>
			<p>为患者创建新的医疗档案记录</p>
		</div>

		<!-- 患者选择区域 -->
		<el-card class="patient-select-card">
			<div class="card-header">
				<h2>选择患者</h2>
			</div>
			<div class="patient-select-form">
				<el-input
					placeholder="输入患者姓名或诊疗号搜索"
					v-model="patientSearchKeyword"
					clearable
					style="width: 300px; margin-right: 15px;"
				>
					<template slot="prepend">患者信息</template>
				</el-input>
				<el-button type="primary" @click="searchPatients" :loading="searchLoading" icon="el-icon-search">
					搜索
				</el-button>
				<el-button type="info" @click="resetPatientSearch" icon="el-icon-refresh">
					重置
				</el-button>
			</div>

			<!-- 患者列表 -->
			<div class="patient-list" v-if="searchResults.length > 0 && hasSearched">
				<el-row :gutter="20">
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" v-for="patient in searchResults" :key="patient.patientId">
						<el-card class="patient-card" shadow="hover">
							<div class="patient-info">
								<div class="info-item">
									<span class="label">患者姓名：</span>
									<span class="value">{{ patient.patientName }}</span>
								</div>
								<div class="info-item">
									<span class="label">诊疗号：</span>
									<span class="value">{{ patient.visitId }}</span>
								</div>
								<div class="info-item">
									<span class="label">科室：</span>
									<span class="value">{{ patient.deptName }}</span>
								</div>
								<div class="info-item">
									<span class="label">住院号：</span>
									<span class="value">{{ patient.hospitalizationId || '门诊' }}</span>
								</div>
							</div>
							<el-button type="primary" size="small" @click="selectPatient(patient)">
								选择患者
							</el-button>
						</el-card>
					</el-col>
				</el-row>
			</div>

			<!-- 空状态 -->
			<div class="empty-state" v-else-if="hasSearched && !searchLoading">
				<el-empty description="暂无患者数据" :image-size="100" />
			</div>

			<!-- 已选患者信息 -->
			<div class="selected-patient" v-if="selectedPatient">
				<el-card class="selected-patient-card" type="success">
					<div class="card-header">
						<h3>已选患者</h3>
						<el-button type="danger" size="mini" @click="clearSelectedPatient" icon="el-icon-close">
							清除选择
						</el-button>
					</div>
					<div class="patient-info">
						<div class="info-item">
							<span class="label">患者姓名：</span>
							<span class="value">{{ selectedPatient.patientName }}</span>
						</div>
						<div class="info-item">
							<span class="label">患者ID：</span>
							<span class="value">{{ selectedPatient.patientId }}</span>
						</div>
						<div class="info-item">
							<span class="label">诊疗号：</span>
							<span class="value">{{ selectedPatient.visitId }}</span>
						</div>
						<div class="info-item">
							<span class="label">科室：</span>
							<span class="value">{{ selectedPatient.deptName }}</span>
						</div>
					</div>
				</el-card>
			</div>
		</el-card>

		<!-- 新建病历表单 -->
		<el-card class="new-record-form-card" v-if="selectedPatient">
			<div class="card-header">
				<h2>病历信息</h2>
			</div>

			<el-form
				ref="newRecordFormRef"
				:model="newRecordForm"
				:rules="newRecordRules"
				label-width="100px"
				class="new-record-form"
			>
				<!-- 病历基本信息 -->
				<el-divider>基本信息</el-divider>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="病历类型" prop="docType">
							<el-select v-model="newRecordForm.docType" placeholder="请选择病历类型" style="width: 100%;">
								<el-option label="入院记录" value="01" />
								<el-option label="病程记录" value="02" />
								<el-option label="出院小结" value="03" />
								<el-option label="门诊病历" value="04" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="病历标题" prop="docTitle">
							<el-input v-model="newRecordForm.docTitle" placeholder="请输入病历标题" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="签名状态" prop="signatureStatus">
					<el-radio-group v-model="newRecordForm.signatureStatus">
						<el-radio label="已签名" />
						<el-radio label="未签名" />
					</el-radio-group>
				</el-form-item>

				<!-- 病历内容 -->
				<el-divider>病历内容</el-divider>

				<el-form-item label="主诉" prop="chiefComplaint">
					<el-input
						v-model="newRecordForm.chiefComplaint"
						type="textarea"
						:rows="2"
						placeholder="请输入患者主诉"
					/>
				</el-form-item>

				<el-form-item label="现病史" prop="historyOfPresentIllness">
					<el-input
						v-model="newRecordForm.historyOfPresentIllness"
						type="textarea"
						:rows="4"
						placeholder="请输入患者现病史"
					/>
				</el-form-item>

				<el-form-item label="既往史" prop="pastHistory">
					<el-input
						v-model="newRecordForm.pastHistory"
						type="textarea"
						:rows="4"
						placeholder="请输入患者既往史"
					/>
				</el-form-item>

				<el-form-item label="体格检查" prop="physicalExam">
					<el-input
						v-model="newRecordForm.physicalExam"
						type="textarea"
						:rows="4"
						placeholder="请输入体格检查结果"
					/>
				</el-form-item>

				<el-form-item label="初步诊断" prop="initialDiagnosis">
					<el-input
						v-model="newRecordForm.initialDiagnosis"
						type="textarea"
						:rows="3"
						placeholder="请输入初步诊断结果"
					/>
				</el-form-item>

				<el-form-item label="检查报告" prop="reportResult">
					<el-input
						v-model="newRecordForm.reportResult"
						type="textarea"
						:rows="4"
						placeholder="请输入检查报告结果"
					/>
				</el-form-item>

				<!-- 表单操作 -->
				<el-form-item>
					<el-button type="primary" @click="submitForm" :loading="submitting" icon="el-icon-check">
						提交
					</el-button>
					<el-button @click="resetForm" icon="el-icon-refresh">
						重置
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script>
	import http from "../../utils/request";

export default {
	name: 'NewMedicalRecord',
	data() {
		return {
			// 患者搜索相关
			patientSearchKeyword: '',
			searchResults: [],
			searchLoading: false,
			hasSearched: false,
			selectedPatient: null,

			// 新建病历表单
			newRecordForm: {
				docType: '',
				docTitle: '',
				signatureStatus: '未签名',
				chiefComplaint: '',
				historyOfPresentIllness: '',
				pastHistory: '',
				physicalExam: '',
				initialDiagnosis: '',
				reportResult: ''
			},

			// 表单验证规则
			newRecordRules: {
				docType: [
					{ required: true, message: '请选择病历类型', trigger: 'change' }
				],
				docTitle: [
					{ required: true, message: '请输入病历标题', trigger: 'blur' },
					{ min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
				],
				chiefComplaint: [
					{ required: true, message: '请输入患者主诉', trigger: 'blur' }
				],
				historyOfPresentIllness: [
					{ required: true, message: '请输入患者现病史', trigger: 'blur' }
				],
				initialDiagnosis: [
					{ required: true, message: '请输入初步诊断结果', trigger: 'blur' }
				]
			},

			// 提交状态
			submitting: false
		}
	},
	methods: {
		// 搜索患者
		async searchPatients() {
			if (!this.patientSearchKeyword) {
				this.$message.warning('请输入搜索关键词');
				return;
			}

			this.searchLoading = true;
			this.hasSearched = true;
			try {
				// 调用后端搜索接口
				try {
					const resp = await http.get(`/doctor/searchPatients`, {
						params: {
							keyword: this.patientSearchKeyword,
                            doctorId: this.$store.state.user.id
						}
					});

					if (resp.data.code === 1) {
						this.searchResults = resp.data.data || [];
					} else {
						this.$message.error(resp.data.msg || '搜索失败');
						this.searchResults = [];
					}
				} catch (apiError) {
					// 如果后端接口调用失败，使用模拟数据并进行过滤
					console.warn('后端接口调用失败，使用模拟数据:', apiError);
					
					// 模拟患者数据
					const mockPatients = [
						{
							patientId: 'P001',
							patientName: '张三',
							visitId: 'V0001',
							deptName: '内科',
							hospitalizationId: 'H0001'
						},
						{
							patientId: 'P002',
							patientName: '李四',
							visitId: 'V0002',
							deptName: '外科',
							hospitalizationId: null
						},
						{
							patientId: 'P003',
							patientName: '王五',
							visitId: 'V0003',
							deptName: '儿科',
							hospitalizationId: 'H0003'
						}
					];

					// 根据搜索关键词过滤模拟数据
					const keyword = this.patientSearchKeyword.toLowerCase();
					this.searchResults = mockPatients.filter(patient => 
						patient.patientName.toLowerCase().includes(keyword) || 
						patient.visitId.toLowerCase().includes(keyword)
					);
				}

			} catch (error) {
				console.error('搜索患者失败:', error);
				this.$message.error('搜索失败，请检查网络连接');
				this.searchResults = [];
			} finally {
				this.searchLoading = false;
			}
		},

		// 重置患者搜索
		resetPatientSearch() {
			this.patientSearchKeyword = '';
			this.searchResults = [];
			this.hasSearched = false;
		},

		// 选择患者
		selectPatient(patient) {
			this.selectedPatient = { ...patient };
			this.searchResults = [];
			this.patientSearchKeyword = '';
			this.hasSearched = false;

			// 自动生成病历标题
			this.generateDocTitle();
		},

		// 清除已选患者
		clearSelectedPatient() {
			this.selectedPatient = null;
		},

		// 生成病历标题
		generateDocTitle() {
			if (!this.selectedPatient || !this.newRecordForm.docType) return;

			const typeMap = {
				'01': '入院记录',
				'02': '病程记录',
				'03': '出院小结',
				'04': '门诊病历'
			};

			const date = new Date().toLocaleDateString();
			this.newRecordForm.docTitle = `${typeMap[this.newRecordForm.docType]}-${this.selectedPatient.patientName}-${date}`;
		},

		// 提交表单
		submitForm() {
			if (!this.selectedPatient) {
				this.$message.warning('请先选择患者');
				return;
			}

			this.$refs.newRecordFormRef.validate(async (valid) => {
				if (valid) {
					this.submitting = true;
					try {
						// 将signatureStatus转换为后端要求的枚举值
						// 0-草稿,1-已签名,2-已归档
						let signatureStatusEnum = 0; // 默认草稿
						if (this.newRecordForm.signatureStatus === '已签名') {
							signatureStatusEnum = 1;
						} else if (this.newRecordForm.signatureStatus === '未签名') {
							signatureStatusEnum = 0; // 未签名对应草稿
						}

						// 构建病历数据
						const medicalRecordData = {
							visitId: this.selectedPatient.visitId,
							docType: this.newRecordForm.docType,
							docTitle: this.newRecordForm.docTitle,
							writerDoctorId: this.$store.state.user.id || this.$store.state.id,
							signatureStatus: signatureStatusEnum,
							hospitalId: this.$store.state.user.hospitalId || 1,
							// 病历内容
							chiefComplaint: this.newRecordForm.chiefComplaint,
							historyOfPresentIllness: this.newRecordForm.historyOfPresentIllness,
							pastHistory: this.newRecordForm.pastHistory,
							physicalExam: this.newRecordForm.physicalExam,
							initialDiagnosis: this.newRecordForm.initialDiagnosis,
							reportResult: this.newRecordForm.reportResult,
							
							// 自动生成的时间
							writerTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
						};

						console.log('提交病历数据:', medicalRecordData);

						// 调用新建病历的接口
						const resp = await http.post('/doctor/newMedicalRecord', medicalRecordData);

						if (resp.data.code === 1) {
							this.$message.success('病历创建成功！');
							this.resetForm();
							this.clearSelectedPatient();
						} else {
							this.$message.error(resp.data.msg || '创建失败');
						}
					} catch (error) {
						console.error('创建病历失败:', error);
						this.$message.error('创建失败，请稍后重试');
					} finally {
						this.submitting = false;
					}
				}
			});
		},

		// 重置表单
		resetForm() {
			this.newRecordForm = {
				docType: '',
				docTitle: '',
				signatureStatus: '未签名',
				chiefComplaint: '',
				historyOfPresentIllness: '',
				pastHistory: '',
				physicalExam: '',
				initialDiagnosis: '',
				reportResult: ''
			};

			if (this.$refs.newRecordFormRef) {
				this.$refs.newRecordFormRef.clearValidate();
			}
		}
	},

	// 监听病历类型变化，自动生成标题
	watch: {
		'newRecordForm.docType'(newVal) {
			if (newVal && this.selectedPatient) {
				this.generateDocTitle();
			}
		}
	}
}
</script>

<style scoped>
	.new-medical-record-container {
		padding: 20px;
		background-color: #f5f7fa;
		min-height: calc(100vh - 84px);
	}

	.page-header {
		margin-bottom: 20px;
	}

	.page-header h1 {
		font-size: 24px;
		font-weight: bold;
		color: #303133;
		margin-bottom: 5px;
	}

	.page-header p {
		font-size: 14px;
		color: #909399;
	}

	.patient-select-card,
	.new-record-form-card {
		margin-bottom: 20px;
		border-radius: 8px;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.card-header h2 {
		font-size: 18px;
		font-weight: bold;
		color: #303133;
		margin: 0;
	}

	.card-header h3 {
		font-size: 16px;
		font-weight: bold;
		color: #303133;
		margin: 0;
	}

	.patient-select-form {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
	}

	.patient-list {
		margin-top: 20px;
	}

	.patient-card {
		transition: transform 0.3s ease;
	}

	.patient-card:hover {
		transform: translateY(-5px);
	}

	.patient-info {
		margin-bottom: 15px;
	}

	.info-item {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
		font-size: 13px;
	}

	.info-item .label {
		min-width: 70px;
		color: #909399;
		margin-right: 10px;
	}

	.info-item .value {
		color: #303133;
		font-weight: 500;
	}

	.empty-state {
		padding: 40px 0;
		text-align: center;
	}

	.selected-patient {
		margin-top: 20px;
	}

	.selected-patient-card {
		border-left: 4px solid #67c23a;
	}

	.new-record-form {
		padding: 0 20px 20px;
	}

	.new-record-form .el-divider {
		margin: 20px 0;
	}

	@media (max-width: 768px) {
		.patient-select-form {
			flex-direction: column;
			align-items: stretch;
			gap: 10px;
		}

		.patient-select-form .el-input {
			width: 100% !important;
			margin-right: 0 !important;
		}

		.card-header {
			flex-direction: column;
			align-items: flex-start;
			gap: 10px;
		}
	}
</style>